package ma.xin.shi;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import ma.xin.shi.configurations.Service.ServiceConfig;
import ma.xin.shi.configurations.Service.ServiceEntry;

public class ServiceUIBinder {

    private final ServiceConfig serviceConfig = ConfigurationManager.getInstance().getServiceConfig();

    // ===== UI 控件引用（可传入）=====
    private final Text serviceNameText;
    private final Text serviceIdText;
    private final Table serviceTable;

    public ServiceUIBinder(Text serviceNameText, Text serviceIdText, Table serviceTable) {
        this.serviceNameText = serviceNameText;
        this.serviceIdText = serviceIdText;
        this.serviceTable = serviceTable;
    }

    /**
     * 从页面读取当前输入值，并尝试添加服务
     */
    public boolean addCurrentServiceFromUI() {
        String name = serviceNameText.getText().trim();
        String idStr = serviceIdText.getText().trim();

        if (name.isEmpty()) return false;

        int id;
        try {
            id = Integer.decode(idStr);
        } catch (NumberFormatException e) {
            return false;
        }

        boolean success = serviceConfig.addServiceEx(name, id);
        if (success) {
            refreshServiceTable();
            clearInputFields();
        }
        return success;
    }

    /**
     * 刷新服务表格，显示所有服务
     */
    public void refreshServiceTable() {
        serviceTable.removeAll();

        for (ServiceEntry entry : serviceConfig.getAllServices()) {
            TableItem item = new TableItem(serviceTable, SWT.NONE);
            item.setText(new String[]{
                String.valueOf(serviceTable.getItemCount() + 1),
                entry.getServiceName(),
                String.format("0x%X", entry.getServiceId())
            });
        }
    }

    /**
     * 清空输入框
     */
    public void clearInputFields() {
        serviceNameText.setText("");
        serviceIdText.setText("");
    }

    /**
     * 将指定服务信息填充到输入框（编辑模式）
     */
    public void loadServiceToInput(ServiceEntry entry) {
        if (entry != null) {
            serviceNameText.setText(entry.getServiceName());
            serviceIdText.setText(String.format("0x%X", entry.getServiceId()));
        }
    }
}
